package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    @Transactional
    @Override
    public OrderSubmitVO submit(Orders orders) {
        AddressBook address = addressBookMapper.getById(orders.getAddressBookId());
        if (address == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        Long currentId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = ShoppingCart.builder().userId(currentId).build();
        List<ShoppingCart> shoppingCartlist = shoppingCartMapper.findShoppingCartlist(shoppingCart);
        if (shoppingCartlist == null && shoppingCartlist.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
//        Orders orders = new Orders();
//        BeanUtils.copyProperties(orders,orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(address.getPhone());
        orders.setAddress(address.getProvinceName() + address.getCityName() + address.getDistrictName() + address.getDetail());
        orders.setConsignee(address.getConsignee());
        orders.setUserId(currentId);
        orderMapper.insert(orders);
        List<OrderDetail> orderDetailList = new ArrayList<>();
        //封装订单明细
        for (ShoppingCart cart : shoppingCartlist) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        //插入订单明细
        orderMapper.insertBatch(orderDetailList);
        //清空购物车
        shoppingCartMapper.clean(currentId);
        //封装OrderSubmitVO
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder().id(orders.getId()).orderTime(orders.getOrderTime()).orderNumber(orders.getNumber()).orderAmount(orders.getAmount()).build();
        return orderSubmitVO;
    }

    @Override
    public void updatePaymentSuccessfulMsg(OrdersPaymentDTO ordersPaymentDTO) {
        //   更新送达时间    o.getCheckoutTime()-o.getOrderTime() +o.getEstimatedDeliveryTime()
        Orders o = orderMapper.getOrdersByOrderNumber(ordersPaymentDTO.getOrderNumber());
        // 订单结账时间
        LocalDateTime checkoutTime = LocalDateTime.now();
        // 订单下单时间
        LocalDateTime orderTime = o.getOrderTime();
        // 计算时间差
        Duration timeDifference = Duration.between(orderTime, checkoutTime);
        // 计算新的送达时间
        LocalDateTime newDeliveryTime = checkoutTime.plus(timeDifference);
        Orders build = Orders.builder().number(ordersPaymentDTO.getOrderNumber()).payMethod(ordersPaymentDTO.getPayMethod()).checkoutTime(checkoutTime).payStatus(Orders.PAID).status(Orders.TO_BE_CONFIRMED).estimatedDeliveryTime(newDeliveryTime).build();
        orderMapper.update(build);
        //websocket
        Map map = new HashMap();
        map.put("type", 1);//1来单提醒2客户催单
        map.put("orderId", build.getNumber());
        map.put("content", "订单号:" + ordersPaymentDTO.getOrderNumber());
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }

    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<OrdersDTO> page = orderMapper.pageQuery(ordersPageQueryDTO);
        long total = page.getTotal();
        return new PageResult(total, page.getResult());
    }

    @Override
    public void updateStatus(Orders orders) {
        orderMapper.update(orders);
    }

    @Override
    public OrdersDTO orderDetailById(Long id) {
        OrdersDTO ordersDTO = orderMapper.ordersDTOById(id);
        return ordersDTO;
    }

    @Override
    public OrderStatisticsVO statistics() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("status",2);
       Integer toBeConfirmed= orderMapper.countByMap(map);
         map.put("status",3);
       Integer confirmed= orderMapper.countByMap(map);
          map.put("status",4);
       Integer deliveryInProgress= orderMapper.countByMap(map);


        return OrderStatisticsVO.builder().toBeConfirmed(toBeConfirmed).confirmed(confirmed).deliveryInProgress(deliveryInProgress).build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
//    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
//        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//        //json对象转成OrderPaymentVO
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
//
//        return vo;
//    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
//    public void paySuccess(String outTradeNo) {
//
//        // 根据订单号查询订单
//        Orders ordersDB = orderMapper.getByNumber(outTradeNo);
//
//        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
//        Orders orders = Orders.builder()
//                .id(ordersDB.getId())
//                .status(Orders.TO_BE_CONFIRMED)
//                .payStatus(Orders.PAID)
//                .checkoutTime(LocalDateTime.now())
//                .build();
//
//        orderMapper.update(orders);
//    }
}
